﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using TerrainProcessor;

namespace ScorchedTanks
{
    class Tank : Actor3d
    {
        public Matrix orientation = Matrix.Identity;

         HeightMapInfo HInfo;

        public Tank(ContentManager content, HeightMapInfo hi, String model)
        {
            mModel = content.Load<Model>(model);
            HInfo = hi;
            direction = new Vector3(0, 0, 1);
            
        }

        public override void Draw(GraphicsDeviceManager g, Camera cam)
        {
            
            Matrix[] transforms = new Matrix[mModel.Bones.Count];
            mModel.CopyAbsoluteBoneTransformsTo(transforms);

            Matrix worldMatrix = orientation * Matrix.CreateTranslation(position);
            foreach (ModelMesh mesh in mModel.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = transforms[mesh.ParentBone.Index] * worldMatrix;
                    effect.View = Matrix.CreateLookAt(cam.GetPosition(), cam.GetLookAt(), Vector3.Up);
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 4 / 3, 1, 10000);

                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;
                }
                mesh.Draw();
            }
        }


        public override void update(float dTime)
        {
            Vector3 normal = HInfo.GetNormal(position);
            float h = HInfo.GetHeight(position);
            position.Y = h;

            orientation.Up = normal;

            orientation.Forward = -direction;
            orientation.Forward = Vector3.Normalize(orientation.Forward);

            orientation.Right = Vector3.Cross(orientation.Forward, orientation.Up);
            orientation.Right = Vector3.Normalize(orientation.Right);

        }
        
        public void Walkto(Vector3 newPosition, bool forward)
        {
            if (HInfo.IsOnHeightmap(newPosition))
            {
                float h = HInfo.GetHeight(newPosition);
                newPosition.Y = h;
                position = newPosition;
            }

        }
    }
}
